<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :disabled="finished"
    >
      <!-- 上拉加载 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <!-- 循环渲染文章的列表 -->
        <art-item
          v-for="item in artlist"
          :key="item.art_id"
          :article="item"
          @remove-article="removeArticle"
        ></art-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArtListApi } from '../../api/homeAPI'
import ArtItem from '../ArtItem/ArtItem.vue'
export default {
  components: {
    ArtItem
  },
  name: 'ArtList',
  props: {
    channelId: {
      type: Number,
      require: true
    }
  },
  data () {
    return {
      artlist: [],
      timestamp: Date.now(),
      loading: true,
      finished: false,
      isLoading: false
    }
  },
  created () {
    this.initArtList()
  },
  methods: {
    // isPullDown是布尔值，如果为true表示用户执行的是下拉刷新的动作
    async initArtList (isPullDown) {
      const { data: res } = await getArtListApi(this.channelId, this.timestamp)
      if (res.message === 'OK') {
        this.timestamp = res.data.pre_timestamp
        // 判断是否为下拉刷新
        if (isPullDown) {
          // 新数据在前，旧数据再后
          this.artlist = [...res.data.results, ...this.artlist]
          this.isLoading = false
        } else {
          // 旧数据在前，新数据再后
          this.artlist = [...this.artlist, ...res.data.results]
          this.loading = false
        }
      }
      if (res.data.pre_timestamp === null) {
        this.finished = true
      }
    },
    onLoad () {
      console.log('触发上拉加载')
      this.initArtList()
    },
    onRefresh () {
      console.log('触发下拉加载')
      this.initArtList(true)
    },
    removeArticle (id) {
      // 对原数组进行 filter 方法的过滤
      this.artlist = this.artlist.filter(item => item.art_id.toString() !== id)

      // 删除文章后 判断文章的长度是否小于10
      // 如果小于10 重新发送请求获取数据
      if (this.artlist.length < 10) {
        this.initArtList()
      }
    }
  }

}
</script>

<style lang="scss" scoped>
</style>
